package com.tadpole.music.view.activity.me;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.tadpole.music.R;
import com.tadpole.music.bean.home.UserInfoBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.home.UserInfoIView;
import com.tadpole.music.iView.login.RegisterIView;
import com.tadpole.music.presenter.home.UserInfoPresenter;
import com.tadpole.music.presenter.me.UpdateUserInfoPresenter;
import com.tadpole.music.utils.DateUtils;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.PictureFileUtil;
import com.tadpole.music.utils.QiniuUploadMoreUtil;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.widget.GenderDialog;
import com.tadpole.music.view.widget.NiceImageView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 个人信息
 * Created By 孙岩
 * on 2020/9/27
 */
public class UserInfoActivity extends BaseActivity implements UserInfoIView, RegisterIView {
    private static int REQUEST_CODE_OPEN_IMAGE_ONE = 0x01;
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //头像
    private NiceImageView ivImage;
    //拍照和照片中选择
    private ImageView ivIcon;
    //修改昵称
    private RelativeLayout llNickName;
    //昵称
    private TextView tvNickName;
    //修改性别
    private RelativeLayout llNickGender;
    //性别
    private TextView tvGender;
    //修改出生日期
    private RelativeLayout llBirth;
    //出生日期
    private TextView tvBirthday;
    //获取用户信息
    private UserInfoPresenter userInfoPresenter;
    //性别数据
    private List<String> listGender;

    //修改信息的presenter
    private UpdateUserInfoPresenter updateUserInfoPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initViews();
        initListeners();
        initData();

        userInfoPresenter = new UserInfoPresenter();
        userInfoPresenter.attachView(this);
        userInfoPresenter.getUserInfo();

        updateUserInfoPresenter = new UpdateUserInfoPresenter();
        updateUserInfoPresenter.attachView(this);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        actionbar_title.setText("个人信息");
        ivImage = findViewById(R.id.ivImage);
        ivIcon = findViewById(R.id.ivIcon);
        llNickName = findViewById(R.id.llNickName);
        llNickGender = findViewById(R.id.llNickGender);
        tvNickName = findViewById(R.id.tvNickName);
        tvGender = findViewById(R.id.tvGender);
        llBirth = findViewById(R.id.llBirth);
        tvBirthday = findViewById(R.id.tvBirthday);
    }

    //初始化数据
    private void initData() {
        listGender = new ArrayList<>();
        listGender.add("男");
        listGender.add("女");
    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                UserInfoActivity.this.finish();
            }
        });

        //修改昵称
        llNickName.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(UserInfoActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(UserInfoActivity.this, NickNameActivity.class);
                        startActivityForResult(intent, 100);
                    }
                } else {
                    ToastUtils.show("请检查您的网路设置");
                }
            }
        });

        //修改性别
        llNickGender.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(UserInfoActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        GenderDialog dialog = new GenderDialog(UserInfoActivity.this, R.style.Dialog_NoTitle, listGender, "性别");
                        dialog.initView(new GenderDialog.IModeSelection() {
                            @Override
                            public void getMode(String mode) {
                                tvGender.setText(mode);
                                if (mode.equals("男")) {
                                    updateUserInfoPresenter.updateUserInfo(4, "1");
                                } else if (mode.equals("女")) {
                                    updateUserInfoPresenter.updateUserInfo(4, "2");
                                }
                            }
                        });
                        dialog.show();
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //拍照和照片中选择
        ivIcon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(UserInfoActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        andPermission();
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //出生日期
        llBirth.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if (SpUtil.getInstance(UserInfoActivity.this).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        showTime();
                    }
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    //展示出生日期
    private void showTime(){
        new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = Mutils.getDate(millseconds);
                        updateUserInfoPresenter.updateUserInfo(3,text);
                    }
                })
                .setThemeColor(getResources().getColor(R.color.color_6d))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.color_6d))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.black))
                .setWheelItemTextSize(13)
                .setTitleStringId("出生日期")
                .setCyclic(false)
                .setMinMillseconds(DateUtils.convertDateToLong("1940-1-1"))
                .setCurrentMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis())
                .build()
                .show(getSupportFragmentManager(), "hours_mins");
    }


    //权限
    @SuppressLint("CheckResult")
    private void andPermission() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission
                .request(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                //请求权限成功
                if (aBoolean) {
                    PictureFileUtil.openGalleryPicture(UserInfoActivity.this, REQUEST_CODE_OPEN_IMAGE_ONE);
                } else {//失败
                    String msg = "请点击【去授权】打开相应权限！";
                    showAlert(msg);
                }
            }
        });
    }

    //授权
    public void showAlert(String msg) {
        new AlertDialog.Builder(this).setMessage(msg).
                setPositiveButton("去授权",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setCancelable(true).show();
    }

    @Override
    public void showUserInfo(UserInfoBean.DataBean bean) {
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.nomel_icon)
                .error(R.mipmap.nomel_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        if (bean.getAvatar().equals("")) {
            Glide.with(this).load(R.mipmap.app_icon).apply(requestOptions).into(ivImage);
        } else {
            Glide.with(this).load(bean.getAvatar()).apply(requestOptions).into(ivImage);
        }

        if (bean.getNickname().equals("")) {
            tvNickName.setText("蝌蚪音基会员");
        } else {
            tvNickName.setText(bean.getNickname());
        }

        if (bean.getGender()==-1||bean.getGender()==0) {
            tvGender.setText("不详");
        } else if(bean.getGender()==1){
            tvGender.setText("男");
        }else if(bean.getGender()==2){
            tvGender.setText("女");
        }

        if(bean.getBirthday().equals("")){
            tvBirthday.setText("暂无");
        }else{
            tvBirthday.setText(bean.getBirthday());
        }
    }

    @Override
    public void noLogin() {
        Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
        startActivity(intent);
        SpUtil.getInstance(this).putString(Constant.TOKEN, "");
    }

    @Override
    public void showResult() {
        ToastUtils.show("修改成功");
        userInfoPresenter.getUserInfo();
    }

    @Override
    public void show401() {
        SpUtil.getInstance(this).putString(Constant.TOKEN, "");
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 100) {
            userInfoPresenter.getUserInfo();
        }else if(resultCode==RESULT_OK&&requestCode==REQUEST_CODE_OPEN_IMAGE_ONE){
            List<LocalMedia> pictureList = PictureSelector.obtainMultipleResult(data);
            if(pictureList.size()==0){
                ToastUtils.show("请选择本人照片");
            }else{
                uploadAvatar(pictureList.get(0).getPath());
            }
        }
    }

    //七牛上传图片
    private void uploadAvatar(String path) {
        final QiniuUploadMoreUtil qiniuUploadMoreUtil = new QiniuUploadMoreUtil();
        qiniuUploadMoreUtil.upLoadFileToQiNiu(this,0, 1, path);
        qiniuUploadMoreUtil.setQiniuUtilI(new QiniuUploadMoreUtil.QiniuUtilI() {
            @Override
            public void succeed(boolean allok, int current, String qiNiuBackPicPath) {
                RequestOptions requestOptions = new RequestOptions()
                        .placeholder(R.mipmap.app_icon)
                        .error(R.mipmap.app_icon)
                        .priority(Priority.HIGH)
                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                if (allok) {
                    updateUserInfoPresenter.updateUserInfo(2,qiNiuBackPicPath);
                    Glide.with(UserInfoActivity.this).load(qiNiuBackPicPath).apply(requestOptions).into(ivImage);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.show("七牛上传失败");
                        }
                    });
                }
            }

            //七牛上传失败
            @Override
            public void failure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.show("七牛上传失败");
                    }
                });
            }

            //七牛上传中
            @Override
            public void progress(int current, int progress) {
            }
        });
    }

}
